<template>
  <div>
  <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
     <!--主表区域 -->
     <a-tab-pane tab="客户跟进表" :key="refKeys[0]" :forceRender="true" :style="tabsStyle">
       <BasicForm @register="registerForm" ref="formRef"/>
     </a-tab-pane>
  <!--子表单区域 -->
      <a-tab-pane tab="跟进计划信息" key="followPlan" :forceRender="true" :style="tabsStyle">
        <!-- 跟进计划文件上传组件 -->
        <div v-if="formModel.id" class="file-upload-section">
          <a-divider>跟进计划文件</a-divider>
          <FollowPlanFileUploader 
            :followPlanId="formModel.id" 
            :disabled="formDisabled"
            v-model:fileList="planFileList"
            @fileUploaded="handlePlanFileUploaded"
            @fileDeleted="handlePlanFileDeleted"
          />
        </div>
        
        <JVxeTable
          keep-source
          resizable
          ref="followPlan"
          v-if="followPlanTable.show"
          :loading="followPlanTable.loading"
          :columns="followPlanTable.columns"
          :dataSource="followPlanTable.dataSource"
          :height="340"
          :disabled="formDisabled"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
          />
      </a-tab-pane>
      <a-tab-pane tab="跟进记录信息" key="followUpContent" :forceRender="true" :style="tabsStyle">
        <!-- 跟进记录文件上传组件 -->
        <div v-if="formModel.id" class="file-upload-section">
          <a-divider>跟进记录文件</a-divider>
          <FollowUpContentFileUploader 
            :followUpContentId="formModel.id" 
            :disabled="formDisabled"
            v-model:fileList="contentFileList"
            @fileUploaded="handleContentFileUploaded"
            @fileDeleted="handleContentFileDeleted"
          />
        </div>
        
        <div style="margin-bottom: 10px; text-align: right;">
          <a-button v-if="!followUpContentEditable" type="primary" @click="followUpContentEditable = true">修改</a-button>
          <a-button v-else type="primary" @click="handleConfirmEdit">确认修改</a-button>
        </div>
        <JVxeTable
          keep-source
          resizable
          ref="followUpContent"
          v-if="followUpContentTable.show"
          :loading="followUpContentTable.loading"
          :columns="followUpContentTable.columns"
          :dataSource="followUpContentTable.dataSource"
          :height="340"
          :disabled="!followUpContentEditable"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
          />
      </a-tab-pane>
    </a-tabs>

    <div style="width: 100%;text-align: center;margin-top: 10px;" v-if="showFlowSubmitButton">
      <a-button preIcon="ant-design:check-outlined" style="width: 126px" type="primary" @click="handleSubmit">提 交</a-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
    import { defHttp } from '/@/utils/http/axios';
    import {ref, computed, unref,reactive, onMounted, defineProps, watch } from 'vue';
    import {BasicForm, useForm} from '/@/components/Form/index';
    import { JVxeTable } from '/@/components/jeecg/JVxeTable'
    import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods';
    import {formSchema,followPlanColumns,followUpContentColumns} from '../FollowUp.data';
    import {saveOrUpdate,followPlanList,followUpContentList, getFollowPlanDetail, getFollowUpDetail} from '../FollowUp.api';
    import { VALIDATE_FAILED } from '/@/utils/common/vxeUtils';
    import FollowPlanFileUploader from './FollowPlanFileUploader.vue';
    import FollowUpContentFileUploader from './FollowUpContentFileUploader.vue';
    import { message } from 'ant-design-vue';
    
    const refKeys = ref(['followUp','followPlan', 'followUpContent', ]);
    const activeKey = ref('followUp');
    const followPlan = ref();
    const followUpContent = ref();
    const tableRefs = {followPlan, followUpContent, };
    const followPlanTable = reactive({
          loading: false,
          dataSource: [],
          columns:followPlanColumns,
          show: false
    })
    const followUpContentTable = reactive({
          loading: false,
          dataSource: [],
          columns:followUpContentColumns,
          show: false
    })
    const followUpContentEditable = ref(false);
    const props = defineProps({
      formData: { type: Object, default: ()=>{} },
      formBpm: { type: Boolean, default: true }
    });
    
    // 表单数据模型
    const formModel = reactive<any>({
      id: '',
      customerName: '',
      principalName: '',
      group1: '',
      group2: '',
      createTime: '',
    });
    
    // 文件列表
    const planFileList = ref<any[]>([]);
    const contentFileList = ref<any[]>([]);
    
    const formDisabled = computed(()=>{
      if(props.formBpm === true){
        if(props.formData.disabled === false){
          return false;
        }
      }
      return true;
    });
    // 是否显示提交按钮
    const showFlowSubmitButton = computed(()=>{
      if(props.formBpm === true){
        if(props.formData.disabled === false){
          return true
        }
      }
      return false
    });
    
    //表单配置
    const [registerForm, {setProps,resetFields, setFieldsValue, validate}] = useForm({
        labelWidth: 150,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 24}
    });

    onMounted(()=>{
      initFormData();
    });
    
    // 监听ID变化，加载文件列表
    watch(() => formModel.id, (newVal) => {
      if (newVal) {
        loadFileData(newVal);
      } else {
        planFileList.value = [];
        contentFileList.value = [];
      }
    });
    
    // 加载文件数据
    async function loadFileData(id: string) {
      try {
        // 加载跟进计划文件
        const planResult = await getFollowPlanDetail(id);
        if (planResult && planResult.files && Array.isArray(planResult.files)) {
          planFileList.value = planResult.files;
        }
        
        // 加载跟进记录文件
        const contentResult = await getFollowUpDetail(id);
        if (contentResult && contentResult.files && Array.isArray(contentResult.files)) {
          contentFileList.value = contentResult.files;
        }
      } catch (error) {
        console.error('加载文件数据失败:', error);
      }
    }
    
    // 文件上传回调
    function handlePlanFileUploaded(file: any) {
      message.success(`文件 ${file.fileName || '未命名'} 上传成功`);
    }
    
    function handlePlanFileDeleted(file: any) {
      message.success(`文件 ${file.fileName || '未命名'} 删除成功`);
    }
    
    function handleContentFileUploaded(file: any) {
      message.success(`文件 ${file.fileName || '未命名'} 上传成功`);
    }
    
    function handleContentFileDeleted(file: any) {
      message.success(`文件 ${file.fileName || '未命名'} 删除成功`);
    }
    
    //渲染流程表单数据
    const queryByIdUrl = '/followup/followUp/queryById';
    async function initFormData(){
      if(props.formBpm === true){
        await reset();
        let params = {id: props.formData.dataId};
        const data = await defHttp.get({url: queryByIdUrl, params});
        //表单赋值
        await setFieldsValue({
          ...data
        });
        
        // 更新formModel
        Object.assign(formModel, data);
        
        requestSubTableData(followPlanList, {id: data.id}, followPlanTable, ()=>{
          followPlanTable.show = true;
        })
        requestSubTableData(followUpContentList, {id: data.id}, followUpContentTable, ()=>{
          followUpContentTable.show = true;
        })
        // 隐藏底部时禁用整个表单
        setProps({ disabled: formDisabled.value })
      }
    }

    //方法配置
    const [handleChangeTabs,handleSubmit,requestSubTableData] = useJvxeMethod(requestAddOrEdit,classifyIntoFormData,tableRefs,activeKey,refKeys) as any[];
    function handleConfirmEdit() {
      followUpContentEditable.value = false;
      // 可选：自动提交修改
      handleSubmit();
    }
    // 弹窗tabs滚动区域的高度
    const tabsStyle = computed(() => {
      let height: Nullable<string> = null
      let minHeight = '100px'
      // 弹窗wrapper
      let overflow = 'auto';
      return {height, minHeight, overflow};
    })

    async function reset(){
      await resetFields();
      activeKey.value = 'followUp';
      followPlanTable.dataSource = [];
      followUpContentTable.dataSource = [];
    }
    function classifyIntoFormData(allValues) {
         let main = Object.assign({}, allValues.formValue)
         return {
           ...main, // 展开
           followPlanList: allValues.tablesValue[0].tableData,
           followUpContentList: allValues.tablesValue[1].tableData,
         }
       }
    //表单提交事件
    async function requestAddOrEdit(values) {
      //提交表单
      await saveOrUpdate(values, true);
    }
</script>

<style lang="less" scoped>
  /** 时间和数字输入框样式 */
  :deep(.ant-input-number) {
    width: 100%;
  }

  :deep(.ant-calendar-picker) {
    width: 100%;
  }
  
  .file-upload-section {
    margin-top: 16px;
    margin-bottom: 24px;
  }
</style>

<style lang="less">
// Online表单Tab风格专属样式
.j-cgform-tab-modal {
  .ant-modal-header {
    padding-top: 8px;
    padding-bottom: 8px;
    border-bottom: none !important;
  }

  .ant-modal .ant-modal-body > .scrollbar,
  .ant-tabs-nav .ant-tabs-tab {
    padding-top: 0;
  }

  .ant-tabs-top-bar {
    width: calc(100% - 55px);
    position: relative;
    left: -14px;
  }

  .ant-tabs .ant-tabs-top-content > .ant-tabs-tabpane {
    overflow: hidden auto;
  }
}
</style>
